package com.baizhi.aspect;


import com.baizhi.annotation.AddLog;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.service.LogService;
import com.baizhi.util.UUIDUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration    //配置类交给工厂管理
@Aspect          // 该类是一个切面类
public class LogAspect {

    private static final Logger log1 = LoggerFactory.getLogger(LogAspect.class);
    @Resource
    HttpServletRequest request;

    @Resource
    LogService logService;

    //@Around("execution(* com.baizhi.serviceimpl.*.*(..)) && !execution(* com.baizhi.serviceimpl.*.query*(..)")
    @Around("@annotation(com.baizhi.annotation.AddLog)")
    public Object addLog(ProceedingJoinPoint proceedingJoinPoint){

        System.out.println("-----------------进入环绕通知---------------------");

        Admin admin = (Admin) request.getServletContext().getAttribute("admin");
        log1.info("admin:{}",admin);
        //操作的方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //获取方法的signature对象
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        //获取方法
        Method method = signature.getMethod();
        //获取方法上的注解
        AddLog addlog = method.getAnnotation(AddLog.class);

        //获取注解上的属性值
        String value = addlog.value();

        log1.info("操作的方法名：{}",methodName);
        String status = null;
        Object result = null;
        try {
            //放行通知  执行目标方法
            result = proceedingJoinPoint.proceed();
            status="Success(执行成功)";
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            status = "Error(执行失败)";
        }

        Log log = new Log(null, admin.getUsername(), new Date(),methodName+"( "+value+ ")",status);

        log1.info("管理员操作日志：{}",log);

        //添加日志数据到数据库
        logService.add(log);

        return result;
    }
}
